package javabasics.nio;

import java.nio.ByteBuffer;

/**
 * @Author suxiaoxiao
 * @Date 2019/6/2 19:19
 * @Version 1.0
 */
public class Nio {

    /**
     * NIO 中变量概念
     *
     * 位置（position）、容量（capacity）、上限（limit）
     *
     * @param args
     */
    public static void main(String[] args) {
        // 缓冲区大小
        ByteBuffer b = ByteBuffer.allocate(15);
        // limit = 15; capacity = 15; position = 0
        sout(b);

        // 写入 10byte 数据
        for (int i = 0; i < 10; i++) {
            b.put((byte)i);
        }
        // limit = 15; capacity = 15; position = 10
        sout(b);

        // 切换为写模式
        // limit = position;
        // position = 0;
        b.flip();
        // limit = 10; capacity = 15; position = 0
        sout(b);

        for (int i = 0; i < 5; i++) {
            System.out.println(b.get());
        }
        System.out.println();
        // limit = 10; capacity = 15; position = 5
        sout(b);
        b.flip();
        // limit = 5; capacity = 15; position = 0
        sout(b);

        for (int i = 0; i < 5; i++) {
            b.put((byte)i);
        }
        sout(b);
        b.clear();
        sout(b);
        // 读取超过 limit 的数据会报错
        for (int i = 0; i < 10; i++) {
            System.out.println(b.get());
        }
        sout(b);

    }

    private static void sout(ByteBuffer b) {
        System.out.println("limit = " + b.limit() + "; capacity = " + b.capacity() + "; position = " + b.position());
    }

}
